package com.tuliyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tuliyou.common.util.Result;
import com.tuliyou.common.util.UserHolder;
import com.tuliyou.dto.MajorDTO;
import com.tuliyou.dto.PageInfo;
import com.tuliyou.dto.UniversityDTO;
import com.tuliyou.dto.UserFavoriteDTO;
import com.tuliyou.entity.Major;
import com.tuliyou.entity.University;
import com.tuliyou.entity.UserFavorite;
import com.tuliyou.mapper.UserFavoriteMapper;
import com.tuliyou.request.UserFavoriteRequest;
import com.tuliyou.service.UserFavoriteService;
import com.tuliyou.vo.UserFavoriteVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements UserFavoriteService {

    @Resource
    private UserFavoriteMapper userFavoriteMapper;

    @Override
    public Result<UserFavoriteDTO> addFavorite(UserFavoriteRequest request) {
        String code = request.getCode();
        String favoriteType = request.getFavoriteType();
        // 如果收藏中已存在。返回错误提示
        UserFavorite uf = userFavoriteMapper.getByCodeAndFavorite(code, favoriteType);
        if(uf != null && uf.getIsDeleted() == 0) {
            return Result.error("您已经收藏过了");
        } else if(uf != null && uf.getIsDeleted() == 1) {
            Long id = uf.getId();
            int row = userFavoriteMapper.updateByUfId(id,LocalDateTime.now());
            if(row > 0) {
                return Result.success(UserFavoriteDTO.fromUserFavorite(uf));
            } else {
                return Result.error("收藏失败，请重试");
            }
        }
        // 从UserHolder中取得用户id
        Long userId = UserHolder.getUser().getId();
        // 获得一个UserFavorite对象并完成赋值
        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setUserId(userId);
        userFavorite.setCode(code);
        userFavorite.setFavoriteType(favoriteType);
        userFavorite.setIsDeleted(0);
        userFavorite.setCreatedAt(LocalDateTime.now());
        save(userFavorite);
        // 获取刚刚插入的UserFavorite对象并转换为UserFavoriteDTO对象，封装到Result对象中返回
        UserFavorite one = query().eq("user_id", userId).eq("code", code)
                .eq("is_deleted", 0).eq("favorite_type", favoriteType).one();
        return Result.success(UserFavoriteDTO.fromUserFavorite(one));
    }

    @Override
    public Result<PageInfo<UserFavoriteVO>> getFavorites(Integer page, Integer size, String favoriteType) {
        // 获得用户id
        Long userId = UserHolder.getUser().getId();
        // 创建UserFavoriteVO列表
        List<UserFavoriteVO> userFavoriteVOList = new ArrayList<>();
        // 设置分页参数
        PageHelper.startPage(page, size);
        // 根据favoriteType和用户id，查询user_favorite表获得UserFavorite列表
        List<UserFavorite> userFavoriteList = query()
                .eq("user_id", userId)
                .eq("favorite_type", favoriteType)
                .eq("is_deleted", 0).list();
        userFavoriteList.sort((o1, o2) -> o2.getCreatedAt().compareTo(o1.getCreatedAt()));
        Page<UserFavorite> userFavoritePage = (Page<UserFavorite>) userFavoriteList;
        // 创建循环
        for(UserFavorite userFavorite : userFavoritePage){
            // 对于列表中的每一个userFavorite，根据其中的数据查询对应表中的数据(universities/majors)
            // 把查到的数据存储到对应实体类中并把实体类数据转换为DTO数据
            String code = userFavorite.getCode();
            UniversityDTO universityDTO;
            MajorDTO majorDTO;
            if (favoriteType.equals("UNIVERSITY")) {
                University university = userFavoriteMapper.getUniversity(code);
                universityDTO = UniversityDTO.fromUniversity(university);
                majorDTO = null;
            } else {
                Major major = userFavoriteMapper.getMajor(code);
                majorDTO = MajorDTO.fromMajor(major);
                universityDTO = null;
            }
            // 把userFavorite数据和DTO数据放到UserFavoriteVO中
            UserFavoriteVO userFavoriteVO = new UserFavoriteVO();
            userFavoriteVO.setId(userFavorite.getId());
            userFavoriteVO.setUserId(userId);
            userFavoriteVO.setCode(code);
            userFavoriteVO.setFavoriteType(favoriteType);
            userFavoriteVO.setCreatedAt(userFavorite.getCreatedAt());
            userFavoriteVO.setUniversityInfo(universityDTO);
            userFavoriteVO.setMajorInfo(majorDTO);
            // 把每个UserFavoriteVO放到UserFavoriteVO列表中，离开循环
            userFavoriteVOList.add(userFavoriteVO);
        }
        // 把UserFavoriteVO列表放到封装到PageInfo类中
        PageInfo<UserFavoriteVO> pageInfo = new PageInfo<>();
        pageInfo.setCurrent(userFavoritePage.getPageNum()); // 当前页码
        pageInfo.setSize(userFavoritePage.getPageSize()); // 每页条数
        pageInfo.setTotal(userFavoritePage.getTotal()); // 总记录数
        pageInfo.setPages(userFavoritePage.getPages()); // 总页数
        pageInfo.setRecords(userFavoriteVOList);
        // 把PageInfo类封装到Result类中并返回
        return Result.success(pageInfo);
    }

    @Override
    public Result<Boolean> deleteFavorite(Long id) {
        /*int row = userFavoriteMapper.deleteFavorite(id);*/
        int row = userFavoriteMapper.updateByUserFavoriteId(id);
        return Result.success(row > 0);
    }
}
